//
//  NewestDetailViewController.m
//  livingDesign
//
//  Created by dlios on 15-1-28.
//  Copyright (c) 2015年 怡居. 3
#import "NewestDetailViewController.h"
#import "ASIHTTPRequest.h"
#import "NewestDetail.h"
#import "NewestDetailView.h"
#import "NewestDetaileTableViewCell.h"
#import "NewestDetailTableViewCell2.h"
#import "DetailWebViewController.h"
#import "DataBaseHandler.h"

@interface NewestDetailViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, retain) NSMutableArray *detailLabelArr;
@property (nonatomic, retain) NSMutableArray *detailImageArr;
@property (nonatomic, retain) NewestDetail *newestDetail;
@property (nonatomic, retain) NewestDetailView *newestDetailView;
@property (nonatomic, retain) UIButton *shareButton;     // 分享页面
@property (nonatomic, retain) UIButton *collectButton;   // 收藏页面
@property (nonatomic, retain) NSString *strPath1;   // 接口字符串
@property (nonatomic, retain) NSURL *url;   // 本地存储的路径
@property (nonatomic, retain) NSData *data;   // 网络情求数据
@property (nonatomic, retain) NSString *newestPath;

@end

@implementation NewestDetailViewController
- (void)dealloc
{
    [_detailImageArr release];
    [_detailLabelArr release];
    [_newestDetail release];
    [_newestDetailView release];
    [_shareButton release];
    [_collectButton release];
    [_strPath1 release];
    [_url release];
    [_data release];
    [_newestD release];
    [_newestPath release];
    [_dbModel release];
    [super dealloc];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 初始化数组
    self.detailLabelArr = [NSMutableArray array];
    self.detailImageArr = [NSMutableArray array];
    self.view.backgroundColor = [UIColor yellowColor];
    NSLog(@"%@", self.newestD.albumId);

    // 接口路径
    if (self.tag == 1) {
       
        self.strPath1 = self.dbModel.benDiDressURL;
    }
    else
    {
        NSString *strPath = @"http://rm.app.diaoyuweng.com/json_rm.php?action=detail&albumId=";
        NSString *str = [strPath stringByAppendingString:self.newestD.albumId];
        self.strPath1 = [str stringByAppendingString:@"&album_type=4&appCookie=channel_AppStore%20version_4.1.2%20oid_0f607264fc6318a92b9e13c65db7cd3c%20package_com.aslibra.rm.jiaju%20platform_iphone%20ver_8.1.2%20jb_0"];
    }
    
    // 网络请求
    [self requestByASI];
    
    // 界面
    self.newestDetailView = [[NewestDetailView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:self.newestDetailView];
    self.newestDetailView.tableView.delegate = self;
    self.newestDetailView.tableView.dataSource = self;
    
//    [self.newestDetailView setShareTarget:self action:@selector(shareButton:)];
//    [self.newestDetailView setCollectTarget:self action:@selector(collectButton:)];
    
    [self.newestDetailView release];
    [self creatButton];
    
  
    // 获取本地路径
//    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//    // 拼接路径
//    self.newestPath = [NSString stringWithFormat:@"%@/%ld", docPath, [self.strPath1 hash]];
//    
    


    
}

// 创建按钮
- (void)creatButton
{
    self.shareButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 100, self.view.frame.size.height - 150, 50, 50)];
   
    self.shareButton.backgroundColor = [UIColor redColor];
    [self.shareButton addTarget:self action:@selector(shareButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.shareButton setTitle:@"分享" forState:UIControlStateNormal];
    [self.shareButton release];
    
    self.collectButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 100, self.view.frame.size.height - 100, 50, 50)];
    
    self.collectButton.backgroundColor = [UIColor yellowColor];
    [self.collectButton addTarget:self action:@selector(collectButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.collectButton setTitle:@"收藏" forState:UIControlStateNormal];
    [self.collectButton release];
}



// 收藏方法
- (void)shareButton:(UIButton *)button
{
    //
}

- (void)collectButton:(UIButton *)button
{
    // 点击收藏将数据存储到本地
//    [NSKeyedArchiver archiveRootObject:self.data toFile:self.newestPath];
    
    // 点击收藏到数据库
    DataBaseHandler *dataDB = [DataBaseHandler shareInstance];
    [dataDB insertDataWithNewest:self.newestD newestDetail:self.strPath1];
    
    
}


// TableView的协议签订
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{ NSLog(@"%ld", self.detailLabelArr.count + self.detailImageArr.count);
    return self.detailLabelArr.count + self.detailImageArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.detailImageArr.count > indexPath.row / 2 ) {
         static NSString *str = @"cell";
        if (self.detailLabelArr.count > indexPath.row / 2) {
            if (indexPath.row %2 == 0) {
                NewestDetaileTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
                if (cell == nil) {
                    cell = [[[NewestDetaileTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str] autorelease];
                }
                cell.newestDetail = [self.detailImageArr objectAtIndex:indexPath.row / 2] ;
                return cell;
            }
        }
        else
        {
        NewestDetaileTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
        if (cell == nil) {
            cell = [[[NewestDetaileTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str] autorelease];
        }
        cell.newestDetail = [self.detailImageArr objectAtIndex:indexPath.row / 2] ;
        return cell;
        }
     

    }

    static NSString *str = @"cell2";
    NewestDetailTableViewCell2 *cell2 = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell2 == nil) {
        cell2 = [[[NewestDetailTableViewCell2 alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str] autorelease];
    }
    cell2.newestDetail = [self.detailLabelArr objectAtIndex:indexPath.row / 2  ];
    return cell2;
 
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (![[[self.detailImageArr objectAtIndex:indexPath.row / 2] article] hasSuffix:@"|"]) {
        NSString *str = [self.detailImageArr objectAtIndex:indexPath.row / 2];
        DetailWebViewController *detaileWeb = [[DetailWebViewController alloc] init];
        detaileWeb.str = str;
        [self presentViewController:detaileWeb animated:YES completion:^{
            
        }];
    }
}

// 实现协议方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
     if (indexPath.row %2 == 0 || (self.detailImageArr.count > indexPath.row / 2 && self.detailImageArr.count < indexPath.row / 2)) {
         
         return 250;
    }
    NewestDetail *newest = [self.detailLabelArr objectAtIndex:indexPath.row / 2];
    if (newest.article.length > 2) {
        NSString *str = newest.article;
        CGRect rext = [self hightWithStr:str];
        return rext.size.height + 40;
        
    }
    NSString *str = newest.title;
    CGRect rext = [self hightWithStr:str];
    return rext.size.height + 40;
    
}
- (CGRect)hightWithStr:(NSString *)str
{
//    NSLog(@"%@", str);
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:14]};
    CGRect rext = [str boundingRectWithSize:CGSizeMake(self.newestDetailView.tableView.frame.size.width, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rext;
}











//http://rm.app.diaoyuweng.com/json_rm.php?action=detail&albumId=458&album_type=4&appCookie=channel_AppStore%20version_4.1.2%20oid_0f607264fc6318a92b9e13c65db7cd3c%20package_com.aslibra.rm.jiaju%20platform_iphone%20ver_8.1.2%20jb_0
// 网络请求
- (void)requestByASI
{
    // 网络请求
    
    NSURL *url = [NSURL URLWithString:self.strPath1];
    NSLog(@"%@", self.strPath1);
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    request.delegate = self;
    [request startAsynchronous];
}


- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSData *data = [request responseData];
    NSDictionary *detaileDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSArray *tempArr = [detaileDic objectForKey:@"data"];
    for (NSDictionary *tempDic in tempArr) {
        self.newestDetail = [[NewestDetail alloc] init];
        NSDictionary *blockDic = [tempDic objectForKey:@"block"];
        [self.newestDetail setValuesForKeysWithDictionary:blockDic];
        if ([self.newestDetail.article hasPrefix:@"http"]) {
            [self.detailImageArr addObject:self.newestDetail];
        
        }
        else
        {
            if (self.newestDetail.article.length > 2 || self.newestDetail.title.length > 0) {
               
                [self.detailLabelArr addObject:self.newestDetail];
                
            }
        
        }
//        if (self.detailImageArr.count == self.detailLabelArr.count) {
//            [self.newestDetail release];
//        }
//        else if(self.detailImageArr.count > self.detailLabelArr.count)
//        {
//            
//        }
        [self.newestDetail release];
        
    }
    NSLog(@"label+++++++%ld", self.detailLabelArr.count);
    NSLog(@"image+++++++%ld", self.detailImageArr.count);

    [self.newestDetailView.tableView reloadData];
    [self.view addSubview:self.collectButton];
     [self.view addSubview:self.shareButton];
   
    
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSLog(@"no ok");
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
  
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
